﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace XCommunity.Views
{
  public abstract class ViewService
  {



    public ViewService( ICommunityContext context )
    {
      Context = context;
    }



    public ICommunityContext Context
    {
      get;
      private set;
    }


    public virtual void Init()
    {

      InitPlugins();

    }


    protected virtual void InitPlugins()
    {

      Plugins = GetPlugins();
      Array.ForEach( Plugins, plugin => plugin.Init( this ) );

    }


    protected IViewPlugin[] Plugins
    {
      get;
      private set;
    }



    protected virtual IViewPlugin[] GetPlugins()
    {
      return CommunitySystem.Plugins.OfType<IViewPlugin>().ToArray();
    }


    public virtual IViewFilter[] GetFilters( ViewObject view, string propertyName )
    {
      return GetPlugins()
         .Select( plugin => plugin.GetFilter( view, propertyName ) )
         .Where( filter => filter != null )
         .ToArray();
    }

    public virtual IViewPagingFilter[] GetPagingFilters( ViewObject view, string propertyName )
    {
      return GetPlugins()
        .Select( plugin => plugin.GetPagingFilter( view, propertyName ) )
        .Where( filter => filter != null )
        .ToArray();

    }




    public abstract ICommunitySystem CommunitySystem
    {
      get;
    }

    public virtual object GetValue( ViewObject view, string name )
    {
      return null;
    }


    public object GetValue( ViewObject viewObject, PropertyInfo property )
    {
      return property.GetValue( viewObject, new object[0] );

    }
  }
}
